package com.hps.activemq.service.impl;

import com.hps.activemq.aq.Sender;
import com.hps.activemq.entity.Good;
import com.hps.activemq.entity.Order;
import com.hps.activemq.entity.User;
import com.hps.activemq.mapper.GoodMapper;
import com.hps.activemq.mapper.OrderMapper;
import com.hps.activemq.mapper.UserMapper;
import com.hps.activemq.service.GoodService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2019-01-11
 */
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements GoodService {

    private OrderMapper orderMapper;

    private UserMapper userMapper;

    private Sender sender;

    public GoodServiceImpl(OrderMapper orderMapper, UserMapper userMapper, Sender sender) {
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
        this.sender = sender;
    }

    @Override
    public Map<String, Object> buy(Long userId, Long goodId) {
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Good good = selectById(goodId);
        if (good == null) {
            result.put("success", false);
            result.put("msg", "商品不存在");
            return result;
        } else if (good.getStock() <= 0) {
            result.put("success", false);
            result.put("msg", "该商品已售罄");
            return result;
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("msg", "用户不存在");
            return result;
        }
        param.put("user_id", userId);
        param.put("good_id", goodId);
        List<Order> orders = orderMapper.selectByMap(param);
        if (CollectionUtils.isEmpty(orders)) {
            Order order = new Order();
            order.setGoodId(goodId);
            order.setUserId(userId);
            sender.send(order);
            result.put("success", true);
            result.put("msg", "正在下单, 请稍等");
        } else {
            result.put("success", "false");
            result.put("msg", "您已经秒杀过该商品, 不能重复秒杀");
        }
        return result;
    }
}
